package fr.labri.macchiato.feature.distantAccess;

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.rpc.AsyncCallback;

import fr.labri.macchiato.core.technical.Callback;

/**
 * Sends a sparql query to a distant server via the REST protocol
 * 
 * @author Paul Sarraute
 * 
 */
public class RestQueryLauncher {
	//	http://macchiato.fr/Auchan/sparql
	private final String BASE_URL;
	private final static String ACCEPT_JSON = "application/sparql-results+json";

	private RequestBuilder requestBuilder;
	private String queryResult;

	/**
	 * 
	 */
	public RestQueryLauncher(String url) {
		BASE_URL = url;
	//	requestBuilder = new RequestBuilder(RequestBuilder.GET, BASE_URL);
	//	requestBuilder.setHeader("Content-Type",
	//			"application/x-www-form-urlencoded");
	}

	private void sendQuery(String query, final Callback<String> callback)
			throws RequestException {
	//	StringBuilder stringBuilder = new StringBuilder();
	//	stringBuilder.append(BASE_URL).append("?query=").append(query);

	//	String test = "http://macchiato.fr/Carrefour/query?query=PREFIX+gr%3A%3Chttp%3A%2F%2Fpurl.org%2Fgoodrelations%2Fv1%23%3E+SELECT+DISTINCT+%3Fean+%3Fname+WHERE+%7B+%3Fproduct+a+gr%3AOffering.+%3Fproduct+gr%3AhasEAN_UCC-13+%3Fean.+%3Fproduct+gr%3Aname+%3Fname.+FILTER+regex(%3Fname%2C+%22%5Epain%22%2C+%22i%22).+%7D&sugexp=chrome,mod=18&sourceid=chrome&ie=UTF-8";
		requestBuilder = new RequestBuilder(RequestBuilder.POST, BASE_URL);
		requestBuilder.setHeader("Accept", ACCEPT_JSON);
		requestBuilder.setHeader("Content-Type","application/x-www-form-urlencoded");
		
		System.out.println(query);
		System.out.println(BASE_URL);

		queryResult = null;
		requestBuilder.sendRequest(query, new RequestCallback() {
			public void onResponseReceived(Request request, Response response) {
				queryResult = response.getText();
				System.out.println("res: " +queryResult);
				System.out.println("state: " +response.getStatusText());
				System.out.println("stateCode: " +response.getStatusCode());
				callback.onCallback(queryResult);
			}

			public void onError(Request request, Throwable exception) {
				exception.printStackTrace();
			}
		});
	}

	public void launchQueryForJSON(String query,
			final AsyncCallback<String> callback) {
		//requestBuilder.setHeader("Accept", ACCEPT_JSON);

		try {
			sendQuery(query, new Callback<String>() {

				@Override
				public void onCallback(String result) {
					callback.onSuccess(result);

				}
			});
		} catch (RequestException e) {

			callback.onFailure(e);
		}
	}

}
